//
//  MWMineViewController.swift
//  mggz
//
//  Created by QinWei on 2018/3/12.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class MWMineViewController: WarningBaseController {
    var timeAlert:TWLAlertView?
    fileprivate var _tableView: UITableView!
    fileprivate var isCardSet:Bool?
    fileprivate var signState:SignedType?
    fileprivate var currentModel : ProjectModel?
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView(frame: CGRect.zero, style: .grouped)
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.backgroundColor = UIColor.clear
            _tableView.separatorStyle = .none
            _tableView.showsVerticalScrollIndicator = false
            
            _tableView.register(UserHeaderCell.self, forCellReuseIdentifier: "\(UserHeaderCell.self)")
            _tableView.register(UserCommonCell.self, forCellReuseIdentifier: "\(UserCommonCell.self)")
            
            return _tableView
        }
    }
    fileprivate var itemNames:[[String]]?
    fileprivate var itemImages:[[String]]?
    fileprivate var cTStatus:CertificationStatus?
    fileprivate let itemBackgroundColors = [["", colorWith255RGB(255, g: 206, b: 61),colorWith255RGB(179, g: 172, b: 242),colorWith255RGB(73, g: 169, b: 238)]]
    
    /***本地变量***/
    fileprivate var userInfoModel: UserInfoModel? //用户信息模型
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //self.addSignStateNotificationObserve()
        self.checkCertificationStatus()
        self.setupSalaryCardCount()
        self.setuptableData()
        self.getData()
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        WWProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我"
        self.isCardSet = false
        
        self.view.backgroundColor = colorWith255RGB(248, g: 248, b: 248)
        if #available(iOS 11.0, *) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior.scrollableAxes
        }
        
        //self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试", style: .done, target: self, action: #selector(doRightAction))
        
        NotificationCenter.default.addObserver(self, selector: #selector(doNotificationAction), name: NSNotification.Name.init(rawValue: kNotificationUserInfoChanged), object: nil)
        
        self.baseView.addSubview(self.tableView)
        
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.baseView)
        }
        if #available(iOS 11.0, *) {
            self.tableView.contentInset = UIEdgeInsets(top: -33, left: 0, bottom: 0, right: 0)
        }
        
        self.setuptableData()
        self.setupSalaryCardCount()
    }
    
     func addSignStateNotificationObserve(){
        let noficationName = Notification.Name.init(MWSignStateNotification)
        
        NotificationCenter.default.addObserver(self, selector: #selector(getMWLocationData(notification:)), name: noficationName, object: nil)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    @objc func getMWLocationData(notification:Notification) {
        let userInfo = notification.userInfo as! [String:AnyObject]
        
        if let signStateData = userInfo["sign"] as? SignedType {
            self.signState = signStateData
        }
        
        if let projectModel = userInfo["project"] as? ProjectModel{
            self.currentModel = projectModel
        }
        
    }
    
    fileprivate func setupSalaryCardCount(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
    LCAPiSubManager.request(.GetSalaryCardCountData(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let cardCount:Int = jsonString["Result"] as? Int else{
                    return
                }
                if cardCount > 0{
                    self.isCardSet = true
                }
                self.tableView.reloadData()
            }
        }
    }
    fileprivate func setuptableData(){
        self.itemNames = NSMutableArray() as? [[String]]
        self.itemImages = NSMutableArray() as? [[String]]
        itemNames = [["","我的银行卡","我的保险","设置"]]
        itemImages = [["","au_bank1","Icon_保险","au_set"]]
        self.checkCertificationStatus()
        WWUser.sharedInstance.ensureCertificationStatus { (status) in
            self.cTStatus = status
            if status == CertificationStatus.authenticated{
                itemNames = [["","我的银行卡","我的保险","设置"]]
                itemImages = [["","au_bank1","Icon_保险","au_set"]]
                self.tableView.reloadData()
                
            }else{
                
                itemNames = [["","我的银行卡", "实名认证","我的保险","设置"]]
                itemImages = [["","au_bank1", "Icon_借款资料认证","Icon_保险", "au_set"]]
                self.tableView.reloadData()
                
            }
        }
   }
    private func checkCertificationStatus() {
        CertificationModel.checkCertificationStatus({ (response) in
            if response.success {
                WWUser.sharedInstance.ensureCertificationStatus(self)
            }
            else {
            }
        })
    }
    func doRightAction() {
        let vc = ViewController()
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func doNotificationAction() {
        self.getData()
    }
    
    @objc func doLoginOutAction() {
        
        let alert  = UIAlertController(title: "确认退出吗？", message: nil, preferredStyle: .alert)
        
        let cancel = UIAlertAction(title: "取消", style: .cancel) { (action) in
            
        }
        cancel .setValue(UIColor.black, forKey: "titleTextColor")
        let choose = UIAlertAction(title: "确定", style: .default) { (action) in
            WWUser.sharedInstance.loginOut()
            let vc = LoginViewController()
            UIApplication.shared.delegate?.window!?.rootViewController = vc
            (UIApplication.shared.delegate as! AppDelegate).setTags(nil)
            RemoteNotificationModel.removeClient { (response) in
                if !response.success {
                    
                }
                else {
                    
                }
            }
            TrackUploadService.sharedInstance.stop()
            TrackUploadService.sharedInstance.stopBackGroundLocation()
        }
        alert.addAction(cancel)
        alert.addAction(choose)
        self.present(alert, animated: true) {
            
        }
    }
    
    fileprivate func getData() {
        UserInfoModel.getMigrantWorkInfo { (response) in
            if response.success {
                self.userInfoModel = response.value
                self.tableView.reloadSections(IndexSet.init(integer: 0), with: .automatic)
            }
            else {
                // WWError(response.message)
            }
        }
    }
    
    //alert删除缓存
    fileprivate func alertDeleteCache(completion:@escaping () -> Void) {
        let alertController = UIAlertController(title:"提示", message: "删除缓存？", preferredStyle: .alert)
        
        let okAction = UIAlertAction(title: "确认", style: .default) { (action) in
            Tool.clearCache()
            completion()
        }
        
        let cancenlAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        alertController.addAction(okAction)
        alertController.addAction(cancenlAction)
        self.present(alertController, animated: true, completion: nil)
    }
}
extension MWMineViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return self.itemNames![0].count
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 && indexPath.section == 0 {
            return 90 + 10
        }
        return 45
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 && indexPath.section == 0{//头像
            let cell = tableView.dequeueReusableCell(withIdentifier: "\(UserHeaderCell.self)", for: indexPath) as! UserHeaderCell
            cell.avatarChangeHandler = {[unowned self] in
                self.getData()
            }
            
            if self.userInfoModel != nil {
                cell.bind(self.userInfoModel!)
            }else{
                cell.avatarImageView.image = UIImage.init(named: "scene_touxiang")
                let username = LoginAuthenticationService.getLastUsernameAndPassword().0
                cell.usernameLabel.text = username!+"用户"
            }
            if self.cTStatus == .authenticated{
                cell.stateImage.isHidden = false
            }
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "\(UserCommonCell.self)", for: indexPath) as! UserCommonCell
        cell.accessoryType = .disclosureIndicator
        

        cell.cellImageView.image = UIImage(named: itemImages![indexPath.section][indexPath.row])
        
        cell.itemNameLabel.text = self.itemNames![indexPath.section][indexPath.row]
        if indexPath.row == 1{
            if self.isCardSet == false{
                cell.itemDetailLabel.text = "未绑定"
            }else{
                cell.itemDetailLabel.text = ""
            }
        }else if self.cTStatus != .authenticated{
            if indexPath.row == 2{
                if self.cTStatus == .certificationInProgress{
                    cell.itemDetailLabel.text = "认证中"
                }else if self.cTStatus == .beReturn{
                    cell.itemDetailLabel.text = "被退回"
                }else{
                  cell.itemDetailLabel.text = "未认证"
                 }
            }else{
                cell.itemDetailLabel.text = ""
            }
        }else{
            cell.itemDetailLabel.text = ""
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if cTStatus == .authenticated{
            if indexPath.section == 0 {
                if indexPath.row == 1 {
                   let myBank = MyBankManagerViewController()
                    myBank.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(myBank, animated: true)
                }
                
                if indexPath.row == 2 {
                    let vc = InsureInfoController()
                    vc.hidesBottomBarWhenPushed = true
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                if indexPath.row == 3 {
                    let setting = MWSettingViewController()
                    setting.hidesBottomBarWhenPushed = true
                    setting.cTStatus = self.cTStatus
                    setting.signState = self.signState
                    setting.currentModel = self.currentModel
                self.navigationController?.pushViewController(setting, animated: true)
                }
         }
            }else{
            if indexPath.section == 0 {
                if indexPath.row == 2 {//认证资料
                    
                    if cTStatus == .uncertified{
                        let certification = CertificationFirstPageViewController(nibName: "CertificationFirstPageViewController", bundle: nil)
                        certification.hidesBottomBarWhenPushed = true
                    self.navigationController?.pushViewController(certification, animated: true)
                        
                    }else if cTStatus == .certificationInProgress{
                        let authenData = AuthenDataViewController(nibName: "AuthenDataViewController", bundle: nil)
                        authenData.cTStatus = self.cTStatus
                        authenData.hidesBottomBarWhenPushed = true
                    self.navigationController?.pushViewController(authenData, animated: true)
                    }else if cTStatus == .beReturn{
                        let beReturn = HaveBeenReturnViewController(nibName: "HaveBeenReturnViewController", bundle: nil)
                        beReturn.hidesBottomBarWhenPushed = true
                   self.navigationController?.pushViewController(beReturn, animated: true)
                    }else if cTStatus == .unKnow{
                        QWTextonlyHud("请刷新状态!", target: self.view)
                    }
                }
                if indexPath.row == 1 { //银行卡
                    if cTStatus != .authenticated{
                       self.setCTAlert()
                    }else{
                    let myBank = MyBankManagerViewController()
                    myBank.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(myBank, animated: true)
                        
                    }
                }
                if indexPath.row == 3 {
                    let vc = InsureInfoController()
                    vc.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(vc, animated: true)
                }
                if indexPath.row == 4 {
                    let setting = MWSettingViewController()
                    setting.hidesBottomBarWhenPushed = true
                    setting.cTStatus = self.cTStatus
                    setting.signState = self.signState
                    setting.currentModel = self.currentModel
                self.navigationController?.pushViewController(setting, animated: true)
                }
            }
        }
    }
    fileprivate func setCTAlert(){
        self.timeAlert = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let custom : CTApplicationView = CTApplicationView.init(frame: CGRect(x: 0, y: 0, width: 250, height: 130))
        custom.applicationButton.addTarget(self, action: #selector(applicationAllInfoClick), for: .touchUpInside)
        custom.contentLabel.text = "请认证通过以后再绑定您的银行卡"
        custom.applicationButton.setTitle("开始认证", for: UIControlState.normal)
        custom.cancelButton.addTarget(self, action: #selector(cancelButtonClick), for: .touchUpInside)
        self.timeAlert?.initWithCustomView(custom, frame: CGRect(x: 0, y: 0, width: 250, height: 130))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.timeAlert!)
    }
    
    @objc fileprivate func applicationAllInfoClick(){
        self.timeAlert?.cancleView()
        if cTStatus == .uncertified {
        let certification = CertificationFirstPageViewController(nibName: "CertificationFirstPageViewController", bundle: nil)
        certification.hidesBottomBarWhenPushed = true
    self.navigationController?.pushViewController(certification, animated: true)
            
        }else if cTStatus == .certificationInProgress{
            QWTextonlyHud("认证中无法绑定银行卡", target: self.view)
        }else{
            QWTextonlyHud("未通过认证前无法绑定银行卡", target: self.view)
        }
    }
    @objc fileprivate func cancelButtonClick(){
        self.timeAlert?.cancleView()
    }   
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 0.0001
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.0001
    }
    
}
